package com.zhiwang.planet.mvvm.viewmodel.my

import androidx.lifecycle.MutableLiveData
import com.zhiwang.planet.mvvm.model.ListReponseWrapper
import com.zhiwang.planet.mvvm.model.ResponseWrapper
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.UserDao
import com.zhiwang.planet.mvvm.model.entity.main.UpdateCheck
import com.zhiwang.planet.mvvm.model.request.LogoutRequest
import com.zhiwang.planet.util.*
import io.reactivex.Observable
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import javax.inject.Inject

class AccountRepository @Inject constructor(val restApi: RestApi, val userDao: UserDao) {


    fun <T> wrap(source: Observable<ResponseWrapper<T>>): MutableLiveData<T> {
        val r = MutableLiveData<T>()
        source.arrange(Consumer { r.value = it })
        return r
    }

    fun wrapVoid(source: Observable<ResponseWrapper<Void>>,
                 result: MutableLiveData<Boolean>? = null,
                 err: MutableLiveData<Throwable>? = null) {
        source.arrangeComplete(
                onComplete = Action { result?.value = true },
                onError = { err?.value = it }
        )

    }


    fun <T> observe(source: Observable<ResponseWrapper<T>>, callback: MutableLiveData<T>) {
        source.arrange(onNext = Consumer { callback.value = it })
    }

    fun observeVoid(source: Observable<ResponseWrapper<Void>>,
                    callBack: MutableLiveData<Boolean>,
                    err: MutableLiveData<Throwable>? = null) {
        source.arrangeComplete(onComplete = Action { callBack.value = true },
                onError = { err?.value = it })
    }

    fun checkUpdate() =
            wrap(restApi.checkApkUpdate("http://xq.ji7.com/download/app_android_version"))


    fun logout(result: MutableLiveData<Boolean>, err: MutableLiveData<Throwable>? = null) =
            wrapVoid(restApi.logout(LogoutRequest()), result, err)


}